import 'package:flutter/material.dart';
import 'app_state_notifier.dart';

// 全局状态实例
final appStateNotifier = AppStateNotifier();

class AppNotifierProvider extends StatelessWidget {
  final Widget child;
  
  const AppNotifierProvider({super.key, required this.child});
  
  // 获取状态实例
  static AppStateNotifier of(BuildContext context) {
    final provider = context.dependOnInheritedWidgetOfExactType<_InheritedNotifierProvider>();
    if (provider == null) {
      throw FlutterError(
        'AppNotifierProvider.of() called with a context that does not contain an AppNotifierProvider.',
      );
    }
    return provider.notifier;
  }
  
  @override
  Widget build(BuildContext context) {
    return ChangeNotifierProvider(
      notifier: appStateNotifier,
      child: child,
    );
  }
}

// 内部InheritedWidget用于依赖注入
class ChangeNotifierProvider extends StatefulWidget {
  final AppStateNotifier notifier;
  final Widget child;
  
  const ChangeNotifierProvider({super.key, required this.notifier, required this.child});
  
  @override
  State<ChangeNotifierProvider> createState() => _ChangeNotifierProviderState();
}

class _ChangeNotifierProviderState extends State<ChangeNotifierProvider> {
  @override
  void initState() {
    super.initState();
    // 监听状态变化
    widget.notifier.addListener(_handleChange);
  }
  
  @override
  void didUpdateWidget(covariant ChangeNotifierProvider oldWidget) {
    super.didUpdateWidget(oldWidget);
    if (widget.notifier != oldWidget.notifier) {
      oldWidget.notifier.removeListener(_handleChange);
      widget.notifier.addListener(_handleChange);
    }
  }
  
  @override
  void dispose() {
    widget.notifier.removeListener(_handleChange);
    super.dispose();
  }
  
  void _handleChange() {
    // 当状态变化时通知依赖的widget
    setState(() {});
  }
  
  @override
  Widget build(BuildContext context) {
    return _InheritedNotifierProvider(
      notifier: widget.notifier,
      child: widget.child,
    );
  }
}

// InheritedWidget用于数据共享
class _InheritedNotifierProvider extends InheritedWidget {
  final AppStateNotifier notifier;
  
  const _InheritedNotifierProvider({required this.notifier, required super.child});
  
  @override
  bool updateShouldNotify(_InheritedNotifierProvider oldWidget) {
    return true; // 总是通知更新
  }
}